﻿#include "key.h"

#include "tkc/mem.h"
#include "hmi/hmi.h"
#include "tkc/thread.h"

/*如果使用中文变量，本文件一定要保存为 UTF-8 BOM 格式*/
static int s_value = 0;

#define HMI_PROP_TEMP "温度"

/*回调函数*/
static ret_t hmi_on_prop_change(hmi_t* hmi, const char* name, const value_t* v) {
  if (strcmp(name, "温度") == 0) {
    s_value = value_int(v);
  }

  return RET_OK;
}

static bool_t s_hmi_running = FALSE;
static tk_thread_t* s_hmi_thread = NULL;

static void* hmi_app_func(void* args) {
  u8 key = 0;
  hmi_t* hmi = hmi_create_with_serial("1", hmi_on_prop_change, NULL);

  while (1) {
    key = KEY_Scan(0);
    if (key) {
      switch (key) {
        case KEY2_PRES: {
          s_value = 0;
          break;
        }
        case KEY1_PRES: {
          s_value--;
          break;
        }
        case KEY0_PRES: {
          s_value++;
          break;
        }
        default: {
          break;
        }
      }

      /*修改数据*/
      hmi_set_prop_int(hmi, HMI_PROP_TEMP, s_value);
    } else {
      sleep_ms(10);
    }

    /*分发事件*/
    hmi_dispatch(hmi);
  }

  return 0;
}

ret_t hmi_app_start(const char* device) {
  return_value_if_fail(s_hmi_running == FALSE, RET_OK);
  return_value_if_fail(s_hmi_thread == NULL, RET_FAIL);

  s_hmi_thread = tk_thread_create(hmi_app_func, (void*)device);
  return_value_if_fail(s_hmi_thread != NULL, RET_FAIL);

  tk_thread_set_name(s_hmi_thread, "hmi");
  tk_thread_set_stack_size(s_hmi_thread, 0x2000);

  tk_thread_start(s_hmi_thread);
  s_hmi_running = TRUE;

  return RET_OK;
}

ret_t hmi_app_stop(void) {
  return_value_if_fail(s_hmi_running == TRUE, RET_OK);

  s_hmi_running = FALSE;
  tk_thread_destroy(s_hmi_thread);
  s_hmi_thread = NULL;

  return RET_OK;
}
